﻿using AiMoBridge.Interface.Client;
using AiMoWindows.Server;

namespace AiMoWindows.MainActions.SecondaryActions
{
    class LoginController(string userName, string password, Action<string, string> showMessageFunc)
    {
        readonly Action<string, string> showMessageFunc = showMessageFunc;
        string UserName { get; } = userName;
        string Password { get; } = password;
        public string ExpireDate { get; private set; } = "";
        public string LoginError { get; private set; } = "";
        public bool LoginResult { get; private set; } = false;
        public event EventHandler? OnLoginSuccess;

        public void Login()
        {
            ILoginClient client = GetClient.GetLoginClient();
            LoginResult = client.Login(UserName, Password, out string printError);
            ExpireDate = client.ExpireDate;
            LoginError = printError;
            Controller_OnLoginFinish();
        }
        bool IsEnglish => !Localization.Local.RunningInChinese;
        private void Controller_OnLoginFinish()
        {
            if (LoginResult)
            {
                showMessageFunc(IsEnglish ? $"Expire Date is {ExpireDate}" : $"过期时间 {ExpireDate}",
                    IsEnglish ? "Success" : "成功");
                RememberPassword();
                OnLoginSuccess?.Invoke(this, new EventArgs());
            }
            else
            {
                showMessageFunc(LoginError, IsEnglish ? "Login Fail" : "登录失败");
            }
        }
        public void RememberPassword()
        {
            ExternalSettings.UserName = UserName;
            ExternalSettings.Password = Password;
            ExternalSettings.Save();
        }

        public static bool AutoLogin()
        {
            LoadRemember(out string userName, out string password);
            if (userName.Length >= 3 && password.Length >= 6)
            {
                ILoginClient client = GetClient.GetLoginClient();
                return client.Login(userName, password, out _);
            }
            return false;
        }
        static void LoadRemember(out string userName, out string password)
        {
            ExternalSettings.Load();
            userName = ExternalSettings.UserName;
            password = ExternalSettings.Password;
        }

        /// <summary>
        /// LogOut的时候需要清除记忆
        /// </summary>
        public static void ClearRememberPassword()
        {
            ExternalSettings.UserName = "";
            ExternalSettings.Password = "";
            ExternalSettings.Save();
        }


    }
}
